<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" ref="dataFormRef" @keyup.enter.native="getDataList(1)">
      <el-form-item>
        单位：
        <el-select size="mini" v-model="dataForm.unit" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        账面数量：
        <el-select size="mini" v-model="dataForm.selectValue" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in selectFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        审批状态：
        <el-select size="mini" v-model="dataForm.auditStatus" clearable placeholder="请选择" @change="getDataList()"
          @clear="getDataList()">
          <el-option value="1" label="审批通过"></el-option>
          <el-option value="0" label="未审批"></el-option>
          <el-option value="-1" label="不通过"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        库存/价格/毛利过滤：
        <el-select size="mini" v-model="dataForm.priceField" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in priceFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="dataForm.priceFormula" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in priceFormulas" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.priceValue" clearable type="number" placeholder="库存/价格/毛利"
          @blur="getDataList(1)" @clear="getDataList(1)"></el-input>
      </el-form-item>
      <el-form-item>
        查询过滤：
        <el-select size="mini" v-model="dataForm.queryField" clearable placeholder="请选择" @change="getDataList(1)"
          @clear="getDataList(1)">
          <el-option v-for="item in queryFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable @blur="getDataList(1)"
          @clear="getDataList(1)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="success" @click="getDataList(1)" icon="el-icon-search">查询</el-button>
        <el-button @click="resetForm" size="mini" type="warning" icon="el-icon-refresh-left">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('stock:stocktaking:save')" type="primary" @click="addOrUpdateHandle()"
            icon="el-icon-plus">新增</el-button>
          <el-button size="mini" v-if="isAuth('stock:stocktaking:delete')" type="danger" @click="deleteHandle()"
            icon="el-icon-delete" :disabled="dataListSelections.length <= 0">删除</el-button>
        </el-button-group>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('stock:stocktaking:export')" type="green" @click="exportData"
            class="iconfont icon-topsales" :disabled="dataListSelections.length <= 0">导出</el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;" @cell-click="tableDbEdit" @cell-dblclick="tableDbEdit"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column type="index" header-align="center" align="center" label="#" width="40">
      </el-table-column>
      <el-table-column prop="takingDate" header-align="center" align="center" label="盘点日期" width="120">
      </el-table-column>
      <el-table-column prop="productCode" header-align="center" align="center" label="产品编码" width="120">
      </el-table-column>
      <el-table-column prop="productName" header-align="center" align="center" label="产品名称" width="160" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="bookCount" header-align="center" align="center" label="账面数量" >
      </el-table-column>
      <el-table-column prop="bookFee" header-align="center" align="center" label="账面金额" >
      </el-table-column>
      <el-table-column prop="checkCount" header-align="center" align="center" label="盘点数量"  width="120">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.checkCount" v-if="showInput == `checkCount${scope.row.takingId}`"
            @blur='blurInput(scope.row, "checkCount", scope.row.checkCount)' v-focus>
          </el-input>
          <span v-else class="active-input">{{scope.row.checkCount}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="checkFee" header-align="center" align="center" label="盘点金额">
      </el-table-column>
      <el-table-column prop="profitAndLossCount" header-align="center" align="center" label="损益数量">
      </el-table-column>
      <el-table-column prop="profitAndLossFee" header-align="center" align="center" label="损益金额">
      </el-table-column>
      <el-table-column prop="barCode" header-align="center" align="center" label="条形码"  width="120" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="batchNo" header-align="center" align="center" label="批号"  width="120" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="standard" header-align="center" align="center" label="规格"  width="120" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="unit" header-align="center" align="center" label="单位">
      </el-table-column>
      <el-table-column prop="produceFactory" header-align="center" align="center" label="厂家" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="producingArea" header-align="center" align="center" label="产地" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="tradePrice" header-align="center" align="center" label="批发价">
      </el-table-column>
      <el-table-column prop="produceDate" header-align="center" align="center" label="生产日期" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="expiryDate" header-align="center" align="center" label="有效期" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="genericName" header-align="center" align="center" label="通用名" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="approvalNo" header-align="center" align="center" label="批准文号" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="dosageForm" header-align="center" align="center" label="剂型">
      </el-table-column>
      <el-table-column prop="lotNo" header-align="center" align="center" label="批次号" width="140" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="auditStatus" header-align="center" align="center" label="审核状态">
        <template slot-scope="scope">
          <el-tag type="success" size="mini" v-if="scope.row.auditStatus == 1">审核通过</el-tag>
          <el-tag type="danger" size="mini" v-else-if="scope.row.auditStatus == -1">审核不通过</el-tag>
          <el-tag type="info" size="mini" v-else>未审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditor" header-align="center" align="center" label="审核人">
      </el-table-column>
      <el-table-column prop="auditNote" header-align="center" align="center" label="审核说明">
      </el-table-column>
      <el-table-column prop="storeName" header-align="center" align="center" label="门店名称" v-if="hasRole('role:sys:super:admin')">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.storeName" v-if="showInput == `storeName${scope.row.takingId}`"
            @blur='blurInput(scope.row, "storeName", scope.row.storeName)' v-focus>
          </el-input>
          <span v-else class="active-input">{{scope.row.storeName}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="storeCode" header-align="center" align="center" label="门店编码" v-if="hasRole('role:sys:super:admin')">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.storeCode" v-if="showInput == `storeCode${scope.row.takingId}`"
            @blur='blurInput(scope.row, "storeCode", scope.row.storeCode)' v-focus>
          </el-input>
          <span v-else class="active-input">{{scope.row.storeCode}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" align="center" label="修改时间">
        <template slot-scope="scope">
        </template>
      </el-table-column>
      <el-table-column prop="updateUsername" header-align="center" align="center" label="修改人">
        <template slot-scope="scope">
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <span v-html="scope.row.remark"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-if="isAuth('stock:stocktaking:delete')"
            @click="deleteHandle(scope.row.takingId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './stocktaking-add-or-update'
  import {downLoadFile,hasRole } from '@/utils/myUtil.js'
  import {Loading  } from "element-ui"
  export default {
    data() {
      return {
        dataForm: {
          selectField: '',
          selectValue: '',
          priceField: '',
          priceFormula: '',
          priceValue: '',
          queryField: '',
          key: '',
          unit: '',
        },
        selectFields: [],
        priceFields: [],
        queryFields: [],
        priceFormulas: [],
        units: [],
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        showInput: "",
        oldData: {},
        currentData: {},
        //导入
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "导入药品数据",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          // 上传的地址
          url: `${window.SITE_CONFIG.baseUrl}/stock/stocktaking/importData`
        },
        //上传的文件
        excelList: [],
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getUnits();
      this.initData()
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      async getDataList() {
        this.dataListLoading = true
        const res = await this.$http({
          url: `/stock/stocktaking/page`,
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'dataForm': this.dataForm
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          this.dataList.forEach(item => {
            item.status = item.status == 1 ? true : false
          })
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.takingId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: `/stock/stocktaking/delete`,
            method: 'delete',
            data: this.$http.adornData(ids, false)
          })
          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      resetForm() {
        this.$nextTick(() => {
          this.dataForm = this.$options.data().dataForm
          this.getDataList()
        })
      },
      async saveHandle(row) {
        row.status = row.status ? 1 : 0
        const res = await this.$http({
          url: `/stock/stocktaking/update`,
          method: 'post',
          data: this.$http.adornData(row)
        });
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getDataList();
      },
      // 当input失去光标后进行的操作
      async blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] = 1
          } else if (value === false) {
            row[name] = 0
          }
        }
        this.showInput = ""
        this.currentData = row
      },
      tableDbEdit(row, column, event) {
        this.showInput = column.property + row.takingId;
        this.oldData[column.property] = row[column.property];
      },
      async exportData() {
        const res = await this.$http({
          url: `/stock/stocktaking/exportData`,
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      beforeUpload(file) {
        //截取文件后缀名
        const fileName = file.name.substring(file.name.lastIndexOf('.'));
        if (fileName.toLowerCase() != '.xls' && fileName.toLowerCase() != '.xlsx') {
          this.$message.error('文件必须为.xls或xlsx类型');
          this.fileList = [];
          return false;
        };
        //读取文件大小
        var fileSize = file.size;
        if (fileSize > 3249576) {
          this.uploadShowDialog = false;
          this.$message({
            type: 'error',
            showClose: true,
            duration: 3000,
            message: '文件不能大于3M!'
          });
          return false;
        }
      },
      // excel表上传
      handleUploadChange(file, fileList) {
        if (fileList.length > 0) {
          // 这一步，是展示最后一次选择的文件
          this.fileList = [fileList[fileList.length - 1]];
        }
      },
      //导入按钮
      handleImport() {
        this.upload.open = true;
      },
      //导入提交
      async submitFileForm() {
        if (this.excelList.length === 0) {
          this.$message.warning("请选择文件");
          return;
        }
        if (this.excelList.length > 1) {
          this.$message.warning("每次只能提交一个文件");
          return;
        }
        let formData = new FormData();
        this.excelList.forEach((item) => {
          formData.append("file", item.raw);
        });
        let loadingInstance = Loading.service({
          lock: true, //lock的修改符--默认是false
          text: "导入中", //显示在加载图标下方的加载文案
          spinner: "el-icon-loading", //自定义加载图标类名
          background: "rgba(0, 0, 0, 0.7)", //遮罩层颜色
          target: document.querySelector("#futureTransferDialog"), //loadin覆盖的dom元素节点
        });
        const res = await this.$http({
          url: this.upload.url,
          method: 'post',
          data: formData
        })
        let data = res.data
        if (data && data.code === 0) {
          loadingInstance.close();
          this.$message({
            type: "success",
            message: "导入成功!",
          });
          this.getDataList();
        }
        this.excelList = [];
        this.upload.open = false;
        loadingInstance.close();
        this.dataListLoading = false
      },
      //下载导入模板
      downloadImportTemplate() {
        window.location.href = "http://file.asdzy.com/upload/files/film/品牌模板.xlsx"
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.excelList = fileList;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      onChangeDr(file, fileList) {
        this.excelList = fileList;
      },
      onRemoveDr(file, fileList) {
        this.excelList = fileList;
      },
      cancelFileForm() {
        this.upload.open = false
        this.excelList = [];
      },
      async getUnits() {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': 'UNIT'
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.units = data.data
        }
      },
      initData() {
        let selectFields = [{
          value: '-1',
          label: '账面数量小于盘点数量'
        }, {
          value: '0',
          label: '账面数量等于盘点数量'
        }, {
          value: '1',
          label: '账面数量大于盘点数量'
        }];

        let priceFields = [{
          value: 'trade_price',
          label: '批发价'
        }, {
          value: 'book_count',
          label: '账面数量'
        }, {
          value: 'book_fee',
          label: '账面金额'
        }, {
          value: 'check_count',
          label: '盘点数量'
        },{
          value: 'check_fee',
          label: '盘点金额'
        }, {
          value: 'profit_and_loss_count',
          label: '损益数量'
        }, {
          value: 'profit_and_loss_fee',
          label: '损益金额'
        }];

        let priceFormulas = [{
          value: 'GE',
          label: '大于等于'
        }, {
          value: 'EQ',
          label: '等于'
        }, {
          value: 'GT',
          label: '大于'
        }, {
          value: 'LE',
          label: '小于等于'
        }, {
          value: 'LT',
          label: '小于'
        }, {
          value: 'NE',
          label: '不等于'
        }, ]


        let queryFields = [{
          value: 'product_code',
          label: '编码'
        }, {
          value: 'bar_code',
          label: '条形码'
        }, {
          value: 'product_name',
          label: '产品名称'
        }, {
          value: 'generic_name',
          label: '通用名'
        }, {
          value: 'pinyin',
          label: '助记码'
        }, {
          value: 'producing_area',
          label: '产地'
        }, {
          value: 'produce_factory',
          label: '厂家'
        }, {
          value: 'dosage_form',
          label: '剂型'
        }, {
          value: 'standard',
          label: '规格'
        }, {
          value: 'effect',
          label: '效果'
        }, {
          value: 'approval_no',
          label: '批准文号'
        }]

        this.selectFields = selectFields;
        this.priceFields = priceFields;
        this.priceFormulas = priceFormulas;
        this.queryFields = queryFields;
      },

    },

    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
